<template>
  <div class="add-role">
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()"><i class="el-icon-arrow-left"/>返回</span>
        <span>|</span>
        <span>添加角色</span>
      </div>
      <div class="right">
        黑马程序员
      </div>
    </header>
    <main class="add-main">
      <div class="step-container">
        <el-steps direction="vertical" :active="currentActive">
          <el-step title="角色信息"/>
          <el-step title="权限信息"/>
          <el-step title="检查并完成"/>
        </el-steps>
      </div>
      <!--
        v-if 真实的dom 创建和移除
        v-show 操作的只是css 样式的变化
                  原因: 步骤切换的时候  有可能回退, 保证dom 之前操作过的状态还在
           -->
      <div class="form-container" v-show="currentActive === 1">
        <div class="title">角色信息</div>
        <div class="form">
          <el-form class="form-box" ref="roleForm" :rules="roleRules" :model="roleInfo" label-width="100px">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="roleInfo.roleName" placeholder="请输入角色名称"/>
            </el-form-item>
            <el-form-item label="角色描述" prop="remark">
              <el-input v-model="roleInfo.remark" placeholder="请输入角色描述"/>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="form-container" v-show="currentActive === 2">
        <div class="title">权限配置</div>
        <div class="form">
          <div class="tree-wrapper">
            <div v-for="item in treeList" :key="item.id" class="tree-item">
              <div class="tree-title"> {{ item.title }}</div>
              <el-tree
                ref="tree"
                :props="{ label: 'title', children: 'children' }"
                show-checkbox
                default-expand-all
                node-key="id"
                check-strictly
                :data="item.children"
              >
              </el-tree>
            </div>
          </div>
        </div>
      </div>
      <div class="form-container" v-show="currentActive === 3">
        <div class="title">检查并完成</div>
        <div class="form">
          <div class="info">
            <div class="form-item">角色名称: {{ roleInfo.roleName }}</div>
            <div class="form-item">角色描述: {{ roleInfo.remark }}</div>
            <div class="form-item">权限信息:</div>
            <div v-for="(item, index) in disabledList" :key="index" class="form-item">
              <div class="tree-title"> {{ item.title }}</div>
              <el-tree
                ref="disabledTree"
                :data="item.children"
                :props="{ label: 'title',  disabled: ()=> true }"
                show-checkbox
                default-expand-all
                node-key="id"
                :highlight-current="false"
              >
              </el-tree>
            </div>
          </div>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="prevStep" v-if="currentActive > 1">上一步</el-button>
        <el-button @click="nextStep" type="primary" v-if="currentActive < 3">下一步</el-button>
        <el-button @click="confirmAdd" type="primary" v-if="currentActive === 3">确认添加</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { getTreeListAPI, createRoleUserAPI, getRolePermisionAPI, updateRoleAPI } from '@/api/role'

export default {
  name: 'AddRole',
  data() {
    return {
      currentActive: 1,
      roleInfo: {
        roleName: '',
        remark: ''
      },
      roleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      treeList: [],
      permsList: [],
      disabledList: []
    }
  },
  mounted() {
    this.getTreeList()
    if (this.$route.query.roleId) {
      this.getRoleDetail(this.roleId)
    }
  },
  computed: {
    roleId() {
      return this.$route.query.roleId
    }
  },
  methods: {
    async getRoleDetail(id) {
      const res = await getRolePermisionAPI(id)
      // eslint-disable-next-line no-empty
      if (res.code === 10000) {
        const { roleName, remark, roleId, perms } = res.data
        // 回填基础表单
        this.roleInfo = {
          roleName,
          remark,
          roleId,
          perms
        }
        this.$refs.tree.forEach((node, index) => {
          node.setCheckedKeys(this.roleInfo.perms[index])
        })
      }
    },
    async getTreeList() {
      const res = await getTreeListAPI()
      // eslint-disable-next-line no-empty
      if (res.code === 10000) {
        this.treeList = res.data
        // 在 disabledList 中放一份数据 因为数组时引用类型， 在进行赋值的时候 ，实际上赋值是数据的引用
        // 也就是说  这两份数据实际指向的是同一个内存区域（堆内存） 一个修改 另一个也会受到影响
        // 所以 这里需要进行深拷贝
        this.disabledList = JSON.parse(JSON.stringify(res.data))
      }
    },
    handleClick(index) {
      this.currentActive = index
    },
    prevStep() {
      if (this.currentActive === 1) {
        return false
      }
      this.currentActive--
    },
    nextStep() {
      if (this.currentActive === 3) {
        return false
      }
      // 在角色信息状态下, 进行表单验证
      // 如果校验通过, 才能进入到下一个状态  (this.currentActive++)
      if (this.currentActive === 1) {
        this.$refs.roleForm.validate((valid) => {
          if (valid) {
            // console.log('submit!!')
            this.currentActive++
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
      if (this.currentActive === 2) {
        // 获取角色列表数据
        // this.getTreeList()
        // 选择权限信息的状态
        // 目标:   判断用户至少选择了一项
        // 思路: 获取到用户选择了什么
        this.permsList = []
        this.$refs.tree.forEach((node) => {
          const keys = node.getCheckedKeys()
          this.permsList.push(keys)
        })
        if (this.permsList.flat().length === 0) {
          // 没有选中任何权限
          this.$message.warning('请至少选择一项权限')
          return false
        } else {
          this.currentActive++
          //
          this.$refs.disabledTree.forEach((node, index) => {
            node.setCheckedKeys(this.permsList[index])
          })
        }
      }
      if (this.currentActive === 3) {
        // 权限信息的状态
      }
    },
    async confirmAdd() {
      // 确认添加角色
      // eslint-disable-next-line no-empty
      if (this.roleId) {
        // 编辑
        console.log('================= 编辑 =====================')
        const res = await updateRoleAPI(this.roleInfo)
        if (res.code === 10000) {
          this.$message.success('修改角色成功')
          this.$router.back()
        } else {
          this.$message.error(res.msg)
        }
      } else {
        // 添加
        const data = {
          ...this.roleInfo,
          perms: this.permsList
        }
        const res = await createRoleUserAPI(data)
        if (res.code === 10000) {
          this.$message.success('添加角色成功')
          this.$router.back()
        } else {
          this.$message.error('添加角色失败')
        }
      }
    }
  }

}
</script>
<style scoped lang="scss">
.add-role {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    position: fixed;
    top: 64px;
    bottom: 88px;
    width: 100%;
    overflow-y: auto;
    background: #f4f6f8;
    padding: 20px 230px;
    display: flex;

    .step-container {
      height: 400px;
      width: 200px;
    }

    .form-container {
      flex: 1;
      background-color: #fff;
      overflow-y: auto;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;
        }

        .info {
          font-size: 14px;
          color: #666;

          .form-item {
            margin-bottom: 20px;
          }
        }
      }

      .form-box {
        width: 600px;
        display: flex;
        flex-direction: column;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
    z-index: 10001;
  }

  .tree-wrapper {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;

    .tree-item {
      flex: 1;
      padding: 0px 4px;
      text-align: center;

      .tree-title {
        background: #f5f7fa;
        text-align: center;
        padding: 10px 0;
        margin-bottom: 12px;
      }
    }
  }
}
</style>
